/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.common.security.utils;


import com.comac.ins.common.security.domain.SsoUser;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Objects;

public class CookieUtil {

    private static ThreadLocal<SsoUser> ssoUserThreadLocal = new ThreadLocal<>();

    public static SsoUser getSsoUser() {
        SsoUser ssoUser = ssoUserThreadLocal.get();
        if (Objects.isNull(ssoUser)) {
            ssoUser = new SsoUser();
        }
        return ssoUser;
    }

    public static void setSsoUser(SsoUser ssoUser) {
        ssoUserThreadLocal.set(ssoUser);
    }

    public static String getValue(HttpServletRequest request, String key) {
        Cookie cookie = get(request, key);
        if (cookie != null) {
            return cookie.getValue();
        }
        return null;
    }

    private static Cookie get(HttpServletRequest request, String key) {
        Cookie[] arr_cookie = request.getCookies();
        if (arr_cookie != null) {
            for (Cookie cookie : arr_cookie) {
                if (cookie.getName().equals(key)) {
                    return cookie;
                }
            }
        }
        return null;
    }

    public static String parseStoreKey(String sessionId) {
        if (sessionId != null && sessionId.contains("_")) {
            return sessionId;
        }
        return null;
    }
}
